import wxrequest from './request'
import {getstorage,clearstorage} from './storage'
import {showtoast,showmodel} from './extendapi'
import {env} from './env'
const instance= new wxrequest({
  baseURL:env.baseurl,
  tomeout:6000
})
instance.interceptors.request=(config)=>{
  // 每次发送请求都携带token一起发送
  const token=getstorage("token")
  if(token){
    config.header['token']=token
  }else{

  }
  return config
}
// 响应拦截器
instance.interceptors.response=async(response)=>{
  const {issuccess,data}=response
  // 判断是否响应成功，响应失败进行提示
  if(issuccess){
    return data
  }else{
    showtoast({
      title:"响应异常",
      icon:"error"
    })
  }
  // 根据响应状态码判断token是否失效，失效重新登录
  switch(data.code){
    case 200:
      return data
    case 208:
      const res=await showmodel({
        content:"token失效，请重新登录",
        showCancel:false
      })
      if(res){
        如果服务器认为token不存在重新登录
        clearstorage()
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
      return Promise.reject(response)
    default:
      showtoast({
        title:"程序异常"
      })
      return Promise.reject(response)
  }
  return response
}
export default instance